<!--设置-数据字典-->
<template>
  <div class="dictionary-container">
    <el-row :gutter="20">
      <!-- 左侧树形结构 -->
      <el-col :span="5">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>字典分类</span>
<!--            <el-button-->
<!--              style="float: right; padding: 3px 0"-->
<!--              type="text"-->
<!--              @click="addRootCategory"-->
<!--            >-->
<!--              添加分类项-->
<!--            </el-button>-->
          </div>
          <el-tree
            :data="dictionaryTree"
            node-key="id"
            :props="treeProps"
            :expand-on-click-node="false"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
            :render-content="renderTreeNode"
          ></el-tree>
        </el-card>
      </el-col>

      <!-- 右侧字典项编辑区域 -->
      <el-col :span="19">
        <el-card class="box-card" v-if="currentNode">
          <div slot="header" class="clearfix">
            <span>字典项管理</span>
            <span style="float: right; margin-right: 20px;">
              字典ID: {{ currentNode.id }}
            </span>
          </div>

          <el-form :model="currentNode" label-width="120px">
            <el-form-item label="字典名称：">
              <el-input v-model="currentNode.name" style="width: 300px;"></el-input>
              <el-button type="primary" @click="updateCategory">保存</el-button>
            </el-form-item>

            <el-divider></el-divider>

            <h3>字典项列表</h3>
            <el-table
              :data="currentNode.items"
              border
              row-key="id"
              style="width: 100%; margin-bottom: 20px;"
            >
              <el-table-column prop="id" label="字典项ID" width="380"></el-table-column>
              <el-table-column prop="name" label="字典项名称"></el-table-column>
              <el-table-column label="操作" width="180">
                <template v-slot="scope">
                  <el-button
                    size="mini"
                    @click="editDictionaryItem(scope.$index, scope.row)"
                  >编辑</el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    @click="deleteDictionaryItem(scope.$index)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <div style="margin-top: 20px;">
              <el-button type="primary" @click="addDictionaryItem">新增字典项</el-button>
              <el-button @click="saveDictionary">保存</el-button>
              <el-button @click="cancelEdit">取消</el-button>
            </div>
          </el-form>
        </el-card>

        <!-- 添加/编辑根分类与子分类 -->
        <el-dialog :title="itemDialogTitle" :visible.sync="TreeDialogvisible" width="50%">
          <el-form :model="dictionaryTreeNode" label-width="100px">
            <el-form-item label="根分类ID" v-if="dictionaryTreeNode.id">
              <el-input v-model="dictionaryTreeNode.id" disabled></el-input>
            </el-form-item>
            <el-form-item label="根分类名称" prop="name">
              <el-input v-model="dictionaryTreeNode.name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="TreeDialogvisible = false">取 消</el-button>
            <el-button type="primary" @click="saveDictionaryNode">确 定</el-button>
          </span>
        </el-dialog>


        <!-- 字典项编辑对话框 -->
        <el-dialog :title="itemDialogTitle" :visible.sync="itemDialogVisible" width="50%">
          <el-form :model="currentItem" label-width="100px">
            <el-form-item label="字典项ID" v-if="currentItem.id">
              <el-input v-model="currentItem.id" disabled></el-input>
            </el-form-item>
            <el-form-item label="字典项名称" prop="name">
              <el-input v-model="currentItem.name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="itemDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveDictionaryItem">确 定</el-button>
          </span>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {createdict, querydict, updatedict} from "../../api/InstitutionApi";

export default {
  data() {
    return {
      // 只能在最后一级创建字典项列表
      dictionaryTree: [
        // {
        //   id: '1',
        //   name: '企业信息',
        //   children: [
        //     {
        //       id: '11',
        //       name: '经营类型',
        //       items: [
        //         { id: '54564654', name: '乔老师' },
        //         { id: '54564655', name: '李老师' }
        //       ]
        //     }
        //   ]
        // },
        // {
        //   id: '2',
        //   name: '人才与招聘',
        //   children: [
        //     {
        //       id: '21',
        //       name: '职位类型',
        //       items: []
        //     }
        //   ]
        // },
        // {
        //   id: '3',
        //   name: '运营',
        //   items: []
        // },
        // {
        //   id: '4',
        //   name: '推广员',
        //   items: []
        // },
        // {
        //   id: '5',
        //   name: '分组',
        //   items: []
        // }
      ],
      treeProps: {
        children: 'children',
        label: 'name'
      },
      currentNode: null,
      dictionaryTreeNode:{
        id: '0',
        name: '新分类',
        items: []
      },
      // 当前字典项
      currentItem: {
        id: '',
        name: ''
      },
      TreeDialogvisible: false, ////添加分类树
      itemDialogVisible: false, ////添加字典框
      itemDialogTitle: '新增字典项',
      isEditingItem: false, ///编辑字典项
      editItemIndex: -1,
      reseTreeNodeCode: ''
    }
  },
  created() {
    this.reseTreeNodeCode = ''
    this.selectNode()
    // 默认选中第一个节点
    this.selectFirstNode()
  },
  methods: {
    // 默认选中第一个节点或之前点击的节点
    selectFirstNode() {
      setTimeout(() => {
        if(this.reseTreeNodeCode == '') {
          if (this.dictionaryTree.length > 0) {
            this.currentNode = this.findFirstLeafNode(this.dictionaryTree[0]);
          }
        } else {
            this.currentNode = this.dictionaryTree.find(item => item.id === this.reseTreeNodeCode)
            // console.log('默认之前点击：',this.currentNode)
        }

      },1000)

    },
    // 查找树中的第一个叶子节点
    findFirstLeafNode(node) {
      if (!node.children || node.children.length === 0) {
        return node;
      }
      return this.findFirstLeafNode(node.children[0]);
    },
    // 查询根节点
    selectNode() {
      this.dictionaryTree = []
      querydict({
        dictcode: '0'
      }).then(res => {
        // console.log('根节点：',res)
        let baseinfo = res.data.data.base_info
        for (let i = 0; i < baseinfo.length; i++) {
          this.dictionaryTree.push({
              id: baseinfo[i].dict_code,
              name: baseinfo[i].dict_name,
              desc: baseinfo[i].dict_desc,
              items: []
            }
          )
          //根据父节点获取字典项
          this.selectItem(i,baseinfo[i].dict_code)
        }

      })
    },
    selectItem(index,code) {
      querydict({
        dictcode: code
      }).then(res => {
        // console.log('字典项内容：',res,this.dictionaryTree)
        let iteminfo = res.data.data.base_info
        for (let i = 0; i < iteminfo.length; i++) {
          this.dictionaryTree[index].items.push({
              id: iteminfo[i].dict_code,
              name: iteminfo[i].dict_name,
              desc: iteminfo[i].dict_desc,
            }
          )
        }

      })
    },

    // 树节点点击事件
    handleNodeClick(data,node,hen) {
      console.log('点击-1')
      // 只有叶子节点才能被选中编辑,data为当前节点下的所有子节点的数据
      if (!data.children || data.children.length === 0) {
        this.currentNode = data;
        // 确保items数组存在,若items不存在，就增加一个
        if (!this.currentNode.items) {
          this.$set(this.currentNode, 'items', []);
        }
      }
      console.log('点击：',this.currentNode);
    },
    // 自定义树节点渲染
    renderTreeNode(h, { node, data, store }) {
      // 判断是否为第一层或第二层节点
      const isFirstLevel = !node.parent || node.level === 0;
      const isSecondLevel = node.level === 1;
      return (
        <span class="custom-tree-node">
          <span>{node.label}</span>
          <span>
            <el-button
              size="mini"
              type="text"
              // on-click={(e) => this.updateCategory(data, e)} 编辑
            >

            </el-button>
            <el-button
              size="mini"
              type="text"
              // on-click={(e) => this.removeCategory(node, data, e)} 删除
            >

            </el-button>
          </span>
        </span>
      );
      //   return (
      //   <span class="custom-tree-node">
      //   <span>{node.label}</span>
      //   <span>
      //     {/* 只在第一层和第二层显示添加按钮 */}
      //     { isFirstLevel  && (
      //       <el-button
      //         size="mini"
      //         type="text"
      //         on-click={(e) => {
      //           e.stopPropagation();
      //           this.appendCategory(data, e);
      //         }}
      //       >
      //         编辑
      //       </el-button>
      //     )}
      //     {/* 只在第一层和第二层显示删除按钮 */}
      //     {(isFirstLevel || isSecondLevel) && (
      //       <el-button
      //         size="mini"
      //         type="text"
      //         on-click={(e) => {
      //           e.stopPropagation();
      //           this.removeCategory(node, data, e);
      //         }}
      //       >
      //         删除
      //       </el-button>
      //     )}
      //   </span>
      // </span>
      //   );
    },
    // 添加根分类时弹窗
    addRootCategory() {
      // const newId = this.generateId();
      // this.dictionaryTree.push({
      //   // id: newId,
      //   id: '0',
      //   name: '新分类',
      //   items: []
      // });
      this.dictionaryTreeNode = {
        id: '0',
        name: '',
        items: []
      }
      console.log('添加根分类：', this.dictionaryTree);
      this.itemDialogTitle = '新增根分类';
      this.isEditingItem = false;
      this.TreeDialogvisible = true;
    },
    // 添加根分类保存
    saveDictionaryNode() {
      //  isEditingItem=true编辑，否则添加
      if(this.isEditingItem) {
        console.log('编辑-1',this.dictionaryTreeNode)
        updatedict({
          "parentdictcode":"0",//字典的父节点code
          "dictcode": this.dictionaryTreeNode.id,//字典的节点code
          "dictname": this.dictionaryTreeNode.name,//:字典名称
          "dictdesc": "XXX"//字典描述
        }).then(res => {
          console.log('编辑：', res)
          if(res.msg === '更新字典成功') {
            this.selectNode()
          }
          this.TreeDialogvisible = false;
        })

      }  else {
        createdict({
          "dictcode":"0",//字典的父节点code，顶层的传入’0‘
          "dictname": this.dictionaryTreeNode.name,//:字典名称
          "dictdesc":"xxx" //字典描述
        }).then(res => {
          console.log('存储根分类：', res)
          let dictData = res.data;
          this.dictionaryTree.push({
            id: dictData.dict_code,
            name: dictData.dict_name,
            items:[]
          })
          this.TreeDialogvisible = false;
          this.selectNode()

        })
      }


    },
    // 添加子分类
    // appendCategory(data, e) {
    //   console.log('添加子分类-1：',data)
    //   // 阻止事件冒泡
    //   e.stopPropagation();
    //   // 生成随机ID
    //   const newId = this.generateId();
    //   // 若没有孩子节点，则增加
    //   if (!data.children) {
    //     this.$set(data, 'children', []);
    //   }
    //   // 为孩子节点增加项目，若有，则再增加一个孩子
    //   data.children.push({
    //     id: newId,
    //     name: '新子分类',
    //     items: []
    //   });
    // },
    // 编辑左边树分类项
    updateCategory(data,e) {
      // 阻止事件冒泡
      // e.stopPropagation();
      this.dictionaryTreeNode = this.currentNode
      console.log('编辑左边树：', this.dictionaryTreeNode);

      // this.itemDialogTitle = '编辑根分类';
      // this.TreeDialogvisible = true;
      this.isEditingItem = true;
      this.saveDictionaryNode()
    },
    // 删除分类
    removeCategory(node, data, e) {
      // 防止事件冒泡
      e.stopPropagation();
      this.$confirm('确定删除该分类吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.id === data.id);
        children.splice(index, 1);
        this.$message.success('删除成功');
      });
    },
    // 添加字典项
    addDictionaryItem() {
      this.currentItem = {
        // id: this.generateId(),
        id:'',
        name: ''
      };
      this.itemDialogTitle = '新增字典项';
      this.isEditingItem = false;
      this.itemDialogVisible = true;
    },
    // 编辑字典项
    editDictionaryItem(index, row) {
      this.currentItem = { ...row };
      this.itemDialogTitle = '编辑字典项';
      this.isEditingItem = true;
      this.editItemIndex = index;
      this.itemDialogVisible = true;
    },
    // 保存字典项
    saveDictionaryItem() {
      if (!this.currentItem.name) {
        this.$message.error('请输入字典项名称');
        return;
      }

      if (this.isEditingItem) {
        this.currentNode.items.splice(this.editItemIndex, 1, { ...this.currentItem });
      } else {
        this.currentNode.items.push({ ...this.currentItem });
      }

      if(this.isEditingItem) {
        updatedict({
          "parentdictcode":  this.currentNode.id,//字典的父节点code
          "dictcode": this.currentItem.id,//字典的节点code
          "dictname": this.currentItem.name,//:字典名称
          "dictdesc": "XXX"//字典描述
        }).then(res => {
          console.log('eidtitem:',res)
          if(res.msg === '更新字典成功') {
            this.selectNode()
          }
        })

      } else {
        createdict({
          "dictcode":this.currentNode.id, //字典的父节点code，顶层的传入’0‘
          "dictname": this.currentItem.name, //:字典名称
          "dictdesc":"xxx"  //字典描述
        }).then(res => {
          console.log('字典项：', res)
          setTimeout(() => {
            // let dictItemData = res.data;
            // this.currentNode.items.push({
            //   id: dictItemData.dict_node,
            //   name: dictItemData.dict_name,
            //   desc: dictItemData.dict_desc
            // })
            this.reseTreeNodeCode = this.currentNode.id
            this.selectNode()
            this.selectFirstNode(this.reseTreeNodeCode)
            // this.handleNodeClick(this.currentNode)
          },1000)
        })
      }
      this.itemDialogVisible = false;
      // this.$message.success('保存成功');
    },
    // 删除字典项
    deleteDictionaryItem(index) {
      this.$confirm('确定删除该字典项吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.currentNode.items.splice(index, 1);
        this.$message.success('删除成功');
      });
    },
    // 保存整个字典
    saveDictionary() {
      // 这里应该调用API保存数据
      console.log('保存字典:', this.currentNode);
      this.$message.success('字典保存成功');
    },
    // 取消编辑
    cancelEdit() {
      // 这里可以重置编辑状态
      this.$message.info('已取消编辑');
    },
    // 生成随机ID
    generateId() {
      return Math.floor(Math.random() * 100000000).toString();
    }
  }
}
</script>

<style scoped>
.dictionary-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
  height: calc(100vh - 100px);
  overflow-y: auto;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  margin-right: 100px;
}




.el-divider {
  margin: 15px 0;
}
</style>
